import {
  Autowired,
  ClazzExtendsMap,
  Component,
  Logger,
  SpringStarter,
  Value,
} from 'j-spring';
import { ExpressServer } from 'j-spring-web';
import { Server } from 'socket.io';
import { getSocketHandler } from './socketHandlerPostProcessor';

@Component()
export class SocketIoServerStarter implements SpringStarter {
  @Autowired()
  expressServer: ExpressServer;

  @Autowired()
  log: Logger;

  @Value({ path: 'socket-io.path', remark: 'socket的path设置', force: false })
  socketPath: string = '/';

  @Value({ path: 'socket-io.*', remark: 'socket的跨域设置', force: false })
  origin: string = '*';

  isSpringStater(): boolean {
    return true;
  }
  async doStart(_clazzMap: ClazzExtendsMap): Promise<void> {
    /**
     * 这里的ExpressServer就是HttpServer服务实例  直接沿用之前的端口就行
     *
     */
    const io = new Server(this.expressServer as any, {
      cors: { origin: this.origin },
      path: this.socketPath,
    });

    const handlers = getSocketHandler();

    io.on('connection', (socket) => {
      handlers.forEach((handler) => {
        if (handler.isAutoRegister()) {
          handler.registerEvent(socket, io);
        }
      });
    });

    this.log.info(
      `socket服务启动,沿用web端口,路径:${this.socketPath},源:${this.origin},处理器数量：${handlers.length}`
    );

    handlers.forEach((h, i) => {
      this.log.info(`注册处理器:${i + 1}.${h.getHandlerName()}`);
    });
  }
}
